﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace LingDingSoft.Http
{
    public class ApplicationBodyWriter : IBodyWriter
    {
        private ICollection<KeyValuePair<string, string>> _requestParams;
        private Encoding _coding;
        public ApplicationBodyWriter(ICollection<KeyValuePair<string, string>> requestParams, Encoding coding)
        {
            _requestParams = requestParams;
            _coding = coding;

        }
        public ApplicationBodyWriter(ICollection<KeyValuePair<string, string>> requestParams)
        {
            _requestParams = requestParams;
            _coding = AppConfig.GetEncoding();

        }
        public void Writer(HttpWebRequest request)
        {

            request.ContentType = "application/x-www-form-urlencoded";
             
            var strBuf = new StringBuilder();
            if (_requestParams != null)
            {
                foreach (var item in _requestParams)
                {
                    strBuf.Append(string.Format("&{0}={1}", item.Key, item.Value));
                }
                if (strBuf.Length > 0)
                {
                    strBuf.Remove(0, 1);
                }
            }
             
            request.Method = "post";
            var requestStream = request.GetRequestStream();
            var tempBuffer = _coding.GetBytes(strBuf.ToString());
            requestStream.Write(tempBuffer, 0, tempBuffer.Length);
            requestStream.Close();

        }
    }
}
